package com.topfun.controller;

import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.topfun.utils.Code;
import com.topfun.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;


public class BaseController {
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	public static void writeResult(String data, HttpServletRequest request, HttpServletResponse response) {
		Code code = Code.SUCCESS;
		writeResult(code,data,request,response);
	}

	public static void writeResult(Code code,String data, HttpServletRequest request, HttpServletResponse response) {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("code",code.getCode());
		jsonObject.addProperty("msg",code.getMessage());
		if(!StringUtil.isEmpty(data)){
			jsonObject.addProperty("data", data);
		}
		try {
			response.setContentType("text/plain; charset=utf-8");
			OutputStream os = response.getOutputStream();
			os.write(jsonObject.toString().getBytes("UTF-8"));
			os.flush();
			os.close();
		} catch (JsonIOException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void writeSuccess(HttpServletRequest request, HttpServletResponse response) {
		Code code = Code.SUCCESS;
		writeResult(code,null,request,response);
	}
	public static void writeError(Code code, HttpServletRequest request, HttpServletResponse response) {
		writeResult(code,null,request,response);
	}
}
